/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */

package org.apache.directory.studio.persistence.core;


import org.apache.velocity.app.Velocity;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;


public class CodeGenerator
{
    Collection<String> imports;


    /**
     * This is the method responsible for generating Java bean code from a analyzed entry
     * in LDAP directory
     *
     * @param generatorContext the object with all required information about 
     *        the entry to generate the Java bean class code
     * @param templateFile the Apache Velocity template to be used to generate 
     *        Java bean code for the selected entry
     */
    public void generateCode( CodeGeneratorContext generatorContext, String templateFile )
    {
        GeneratorUtility utility = new GeneratorUtility();
        generateClassTemplate( generatorContext );
        try
        {
            Properties properties = new Properties();
            properties.load( getClass().getResourceAsStream( "/velocity.properties" ) );
            Velocity.init( properties );
            VelocityContext context = new VelocityContext();
            context.put( "package", generatorContext.getPackageName() );
            context.put( "class", generatorContext.getClassName() );
            context.put( "utility", utility );
            context.put( "imports", imports );
            context.put( "entryProps", generateClassTemplate( generatorContext ) );

            Template template = null;
            try
            {
                template = Velocity.getTemplate( templateFile );
            }
            catch ( ResourceNotFoundException rnfe )
            {
                System.out.println( "CodeGenerator : error : cannot find template " + templateFile );
            }
            catch ( ParseErrorException pee )
            {
                System.out.println( "CodeGenerator : Syntax error in template " + templateFile );
            }
            String path = generatorContext.getProjectFolderPath() + "/"
                + generatorContext.getPackageName().replace( ".", "/" );
            new File( path ).mkdirs();
            File javaFile = new File( path + "/" + generatorContext.getClassName() + ".java" );
            BufferedWriter writer = new BufferedWriter( new FileWriter( javaFile ) );
            if ( template != null )
                template.merge( context, writer );
            writer.flush();
        }
        catch ( Exception e )
        {
            System.out.println( e );
        }
    }


    /**
     * This generates the Dao class for the bean class generated for an entry 
     *
     * @param generatorContext the object with all required information about 
     *        the entry to generate the Dao class for bean generated from an entry
     * @param templateFile the Apache Velocity template to be used to generate 
     *        Dao class
     */
    public void generateDaoCode( CodeGeneratorContext generatorContext, String templateFile )
    {
        GeneratorUtility utility1 = new GeneratorUtility();
        generateClassTemplate( generatorContext );
        try
        {
            Properties properties = new Properties();
            properties.load( getClass().getResourceAsStream( "/velocity.properties" ) );
            Velocity.init( properties );
            VelocityContext context = new VelocityContext();
            context.put( "package", generatorContext.getPackageName() );
            context.put( "utility", utility1 );
            context.put( "generator", generatorContext );
            context.put( "entryProps", generateClassTemplate( generatorContext ) );
            Template template = null;
            try
            {
                template = Velocity.getTemplate( templateFile );
            }
            catch ( ResourceNotFoundException rnfe )
            {
                System.out.println( "CodeGenerator : error : cannot find template " + templateFile );
            }
            catch ( ParseErrorException pee )
            {
                System.out.println( "CodeGenerator : Syntax error in template " + templateFile );
            }
            String path = generatorContext.getProjectFolderPath() + "/"
                + generatorContext.getPackageName().replace( ".", "/" );
            new File( path + "/dao" ).mkdirs();
            File javaFile = new File( path + "/dao/" + generatorContext.getClassName() + "Dao.java" );
            BufferedWriter writer = new BufferedWriter( new FileWriter( javaFile ) );
            if ( template != null )
                template.merge( context, writer );
            writer.flush();
        }
        catch ( Exception e )
        {
            System.out.println( e );
        }
    }


    /**
     * This generates the GenericLdapDao abstract class and all the Dao classes generated
     * are inherited from this one
     *
     * @param generatorContext the object with all required information about 
     *        the entry to generate the JGenericLdapDao class 
     * @param templateFile the Apache Velocity template to be used to generate 
     *        GenericLdapDao code for the selected entry
     */
    public void generateGenericDaoCode( CodeGeneratorContext generatorContext, String templateFile )
    {
        GeneratorUtility utility1 = new GeneratorUtility();
        generateClassTemplate( generatorContext );
        try
        {
            Properties properties = new Properties();
            properties.load( getClass().getResourceAsStream( "/velocity.properties" ) );
            Velocity.init( properties );
            VelocityContext context = new VelocityContext();
            context.put( "package", generatorContext.getPackageName() );
            context.put( "utility", utility1 );
            context.put( "generator", generatorContext );
            Template template = null;
            try
            {
                template = Velocity.getTemplate( templateFile );
            }
            catch ( ResourceNotFoundException rnfe )
            {
                System.out.println( "CodeGenerator : error : cannot find template " + templateFile );
            }
            catch ( ParseErrorException pee )
            {
                System.out.println( "CodeGenerator : Syntax error in template " + templateFile );
            }
            String path = generatorContext.getProjectFolderPath() + "/"
                + generatorContext.getPackageName().replace( ".", "/" );
            new File( path + "/dao" ).mkdirs();
            File javaFile = new File( path + "/dao/" + "GenericLdapDao.java" );
            BufferedWriter writer = new BufferedWriter( new FileWriter( javaFile ) );
            if ( template != null )
                template.merge( context, writer );
            writer.flush();
        }
        catch ( Exception e )
        {
            System.out.println( e );
        }
    }

    /**
     * Setup the EntryProperties objects with appropriate writtenJavaType, 
     * writtenMapFromEntry and writtenMapToEntry values. But this method logic
     * should be moved in to velocity templates later
     *
     * @param generatorContext the generator 
     * @return the list of EntryProperties to be generated
     */
    public List<EntryProperties> generateClassTemplate( CodeGeneratorContext generatorContext )
    {
        List<EntryProperties> entryDetails = new ArrayList<EntryProperties>();
        for ( EntryProperties entryProperty : generatorContext.getEntryProperties() )
        {
            if ( entryProperty.isGen() == true )
            {
                entryDetails.add( entryProperty );
            }
        }
        collectImports( entryDetails );
        for ( EntryProperties properties : entryDetails )
        {
            Cardinality cardinality = properties.getCardinality();
            JavaType javaType = properties.getJavaType();
            if ( cardinality == Cardinality.ONE || cardinality == Cardinality.ZERO_OR_ONE )
            {
                if ( javaType == JavaType.BYTE_ARRAY )
                {
                    properties.setWrittenJavaType( properties.getJavaType().toString() );
                    properties.setWrittenMapFromEntry( "getBytes" );
                    properties.setWrittenMapToEntry( "setBytes" );
                }
                else if ( javaType == JavaType.CALENDAR )
                {
                    properties.setWrittenJavaType( properties.getJavaType().toString() );
                    properties.setWrittenMapFromEntry( "getCalendar" );
                    properties.setWrittenMapToEntry( "setCalendar" );
                }
                else
                {
                    properties.setWrittenJavaType( properties.getJavaType().toString() );
                    properties.setWrittenMapFromEntry( "get"
                        + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) );
                    properties.setWrittenMapToEntry( "set"
                        + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) );
                }
            }
            else if ( Cardinality.isArray( cardinality )
                && ( ( javaType == JavaType.STRING ) || ( javaType == JavaType.CALENDAR )
                    || ( javaType == JavaType.INT ) || ( javaType == JavaType.LONG ) || ( javaType == JavaType.BOOLEAN ) || ( javaType == JavaType.BYTE_ARRAY ) ) )
            {
                properties.setWrittenJavaType( javaType + "[]" );
                properties.setWrittenMapFromEntry( "get"
                    + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "Array" );
            }
            else if ( Cardinality.isList( cardinality )
                && ( javaType == JavaType.STRING || javaType == JavaType.CALENDAR ) )
            {
                properties.setWrittenJavaType( "List<" + javaType + ">" );
                if ( javaType == JavaType.CALENDAR )
                {
                    properties.setWrittenMapFromEntry( "getCalendarList" );
                }
                else
                {
                    properties.setWrittenMapFromEntry( "get"
                        + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "List" );
                }
            }
            else if ( Cardinality.isSet( cardinality )
                && ( javaType == JavaType.STRING || javaType == JavaType.CALENDAR ) )
            {
                properties.setWrittenJavaType( "Set<" + javaType + ">" );
                if ( javaType == JavaType.CALENDAR )
                {
                    properties.setWrittenMapFromEntry( "getCalendarSet" );
                }
                else
                {
                    properties.setWrittenMapFromEntry( "get"
                        + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "Set" );
                }
            }
            else if ( ( Cardinality.isSet( cardinality ) ) && ( javaType == JavaType.INT ) )
            {
                properties.setWrittenJavaType( "Set<Integer>" );
                properties.setWrittenMapFromEntry( "getIntegerSet" );
            }
            else if ( ( Cardinality.isSet( cardinality ) ) && ( javaType == JavaType.LONG ) )
            {
                properties.setWrittenJavaType( "Set<Long>" );
                properties.setWrittenMapFromEntry( "get"
                    + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "Set" );
            }
            else if ( ( Cardinality.isSet( cardinality ) ) && ( javaType == JavaType.BOOLEAN ) )
            {
                properties.setWrittenJavaType( "Set<Boolean>" );
                properties.setWrittenMapFromEntry( "get"
                    + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "Set" );
            }
            else if ( ( Cardinality.isSet( cardinality ) ) && ( javaType == JavaType.BYTE_ARRAY ) )
            {
                properties.setWrittenJavaType( "Set<byte[]>" );
                properties.setWrittenMapFromEntry( "getByteArraySet" );
            }
            else if ( ( Cardinality.isList( cardinality ) ) && ( javaType == JavaType.INT ) )
            {
                properties.setWrittenJavaType( "List<Integer>" );
                properties.setWrittenMapFromEntry( "get"
                    + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "List" );
            }
            else if ( ( Cardinality.isList( cardinality ) ) && ( javaType == JavaType.LONG ) )
            {
                properties.setWrittenJavaType( "List<Long>" );
                properties.setWrittenMapFromEntry( "get"
                    + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "List" );
            }
            else if ( ( Cardinality.isList( cardinality ) ) && ( javaType == JavaType.BOOLEAN ) )
            {
                properties.setWrittenJavaType( "List<Boolean>" );
                properties.setWrittenMapFromEntry( "get"
                    + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "List" );
            }
            else if ( ( Cardinality.isList( cardinality ) ) && ( javaType == JavaType.BYTE_ARRAY ) )
            {
                properties.setWrittenJavaType( "List<Byte[]>" );
                properties.setWrittenMapFromEntry( "get"
                    + GeneratorUtility.firstToUpperCase( properties.getJavaType().toString() ) + "List" );
            }
        }
        return entryDetails;
    }


    /**
     * Analyzes for the required packages need to be  imported to the class
     * and add them to a HashSet
     *
     * @param entryDetails the entry details
     */
    private void collectImports( List<EntryProperties> entryDetails )
    {
        imports = new HashSet<String>();
        for ( EntryProperties properties : entryDetails )
        {
            if ( Cardinality.isList( properties.getCardinality() ) )
            {
                imports.add( "java.util.List" );
            }
            if ( Cardinality.isSet( properties.getCardinality() ) )
            {
                imports.add( "java.util.Set" );
            }
        }
    }

}
